import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Card, Button, Input, Table, Switch, Image, message } from "antd";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import axios from "axios";
import { saveProInfo } from "../../redux/action_creators/product_action";
import { connect } from "react-redux";

function Product(props) {
  let [productList, setProductList] = useState([]);
  let [total, setTotal] = useState("");
  let [current, setCurrent] = useState(1);
  let [search, setSearch] = useState("");

  let [isLoading, setIsLoading] = useState(true);
  const navigate = useNavigate();
  const { userInfo } = props;

  useEffect(() => {
    reqProductList(current);
    // eslint-disable-next-line
  }, []);

  const reqProductList = async (current, search) => {
    const responce = await axios.get(
      "http://api.shop.eduwork.cn/api/admin/goods",

      {
        params: { current: current, title: search },
        headers: {
          Authorization: userInfo.token,
        },
      }
    );
    setIsLoading(false);
    setProductList(responce.data.data);
    setTotal(responce.data.meta.pagination.total);
    setCurrent(responce.data.meta.pagination.current_page);

    // 将数据存储到redux中
    props.saveProInfo(responce.data.data);
  };

  const updateStatus = async (id) => {
    const responce = await axios.patch(
      `http://api.shop.eduwork.cn/api/admin/goods/${id}/on`,

      {},
      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    if (responce.status === 204) {
      message.success("商品状态更新成功");
    } else {
      message.error("商品状态更新失败");
    }
  };

  const reqSearch = () => {
    reqProductList(current, search);
  };

  const updateCurrent = (number) => {
    setCurrent(number);
    reqProductList(number, search);
  };

  // timer 必须定义在方法外部，否则不起作用
  let timer = null;
  const updateSearch = (e) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      setSearch(e.target.value);
    }, 1000);
  };

  const columns = [
    {
      title: "商品图片",
      dataIndex: "cover_url",
      width: "150px",
      key: "cover_url",
      render: (cover_url) => {
        return <Image width={100} src={cover_url} />;
      },
    },
    {
      title: "商品名称",
      dataIndex: "title",
      key: "title",
    },

    {
      title: "价格",
      width: "10%",
      align: "center",
      dataIndex: "price",
      key: "price",
      render: (price) => "￥" + price,
    },

    {
      title: "库存",
      width: "10%",
      align: "center",
      dataIndex: "stock",
      key: "stock",
    },
    {
      title: "销量",
      width: "10%",
      align: "center",
      dataIndex: "sales",
      key: "sales",
    },
    {
      title: "是否上架",
      width: "15%",
      align: "center",
      // dataIndex: "is_on",
      key: "is_on",
      render: (item) => {
        return (
          <Switch
            checkedChildren="已上架"
            unCheckedChildren="未上架"
            defaultChecked={item.is_on === 1 ? true : false}
            onChange={() => {
              updateStatus(item.id);
            }}
          />
        );
      },
    },
    {
      align: "center",
      title: "操作",
      width: "15%",
      //dataIndex: "operation",
      key: "operation",
      render: (item) => {
        return (
          <div>
            <Button
              type="link"
              onClick={() => {
                navigate(`detail/${item.id}`);
              }}
            >
              详情
            </Button>
            <br />
            <Button
              type="link"
              onClick={() => {
                navigate(`update/${item.id}`);
              }}
            >
              修改
            </Button>
          </div>
        );
      },
    },
  ];

  return (
    <div>
      <Card
        title={
          <div>
            <Input
              placeholder="请输入商品名"
              style={{ width: "30%", margin: "0px 10px" }}
              allowClear
              onChange={updateSearch}
            />
            <Button type="primary" onClick={reqSearch}>
              <SearchOutlined />
              搜索
            </Button>
          </div>
        }
        extra={
          <Button
            type="primary"
            onClick={() => {
              navigate("add");
            }}
          >
            <PlusOutlined />
            添加商品
          </Button>
        }
      >
        <Table
          dataSource={productList}
          columns={columns}
          loading={isLoading}
          rowKey={"id"}
          pagination={{
            pageSize: 10,
            total: total,
            current: current,
            onChange: updateCurrent,
            showQuickJumper: true,
          }}
          //scroll={{ scrollToFirstRowOnChange: true, y: 350 }}
        />
      </Card>
    </div>
  );
}

export default connect((state) => ({ userInfo: state.userInfo }), {
  saveProInfo,
})(Product);
